import useUserStore from '@/store/user.ts'
import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {getUserInfo} from './router/dynamicRouter'
import {ref} from 'vue'

NProgress.configure({showSpinner: false})
const whiteList: string[] = ['/login', '/403', '/404', '/500']
let isAgainRouter = ref<boolean>(true)

router.beforeEach((to, from, next) => {
	const userStore = useUserStore()
	NProgress.start()
	if (userStore.token) {
		if (to.path === '/login') {
			next({path: '/', replace: true})
			NProgress.done()
		} else {
			if (isAgainRouter.value) {
				getUserInfo().then(() => {
					next({...to, replace: true})
				})
				isAgainRouter.value = false
			} else {
				next()
				NProgress.done()
			}
		}
	} else {
		if (whiteList.includes(to.path)) {
			console.log(from)
			next()
			NProgress.done()
		} else {
			next('/login')
			NProgress.done()
		}
	}
})
